package com.qq.BFMRSE.encrypt;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;

import com.qq.BFMRSE.util.BFConstants;
import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;


public class encryotHelper {
	public static void keyGenAndSava(String keyGenInput,String path){
		String desfileName=path+File.separator+BFConstants.DESKEYFILENAME;
		try {
			//1.初始化key秘钥      
	        KeyGenerator keyGenerator = KeyGenerator.getInstance(BFConstants.ALGORITHM);  
	        keyGenerator.init(new SecureRandom(keyGenInput.getBytes()));  
	        SecretKey secretKey= keyGenerator.generateKey();  
	        //转换key秘钥  
	        DESKeySpec deSedeKeySpec=new DESKeySpec(secretKey.getEncoded());  
	        SecretKeyFactory secretKeyFactory=SecretKeyFactory.getInstance(BFConstants.ALGORITHM);  
	        Key  key= secretKeyFactory.generateSecret(deSedeKeySpec);  
	    //2.对生成的密钥key进行编码保存  
	        String keyencode= HexBin.encode(key.getEncoded());  
	        //写入文件保存  
	        File file=new File(desfileName);  
	        OutputStream outputStream=new FileOutputStream(file);  
	        outputStream.write(keyencode.getBytes());  
	        outputStream.close();  
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	
	}
}
